//
//  MyViewController.m
//  SeaMelonSeeds_Counselor
//
//  Created by 尤振宇 on 2017/7/14.
//  Copyright © 2017年 杨笑. All rights reserved.
//

#import "MyViewController.h"
#import "MyHeaderView.h"
#import "EditDataViewController.h"
#import "SettingTableViewController.h"
#import "AnnouncementViewController.h"
#import "WalletViewController.h"
#import "CompleteOrderViewController.h"
#import "FansTableViewController.h"
#import "EvaluationViewController.h"
#import "ConfigApi.h"

@interface MyViewController ()
@property(nonatomic,strong)MyHeaderView *myHeaderView;
@property(nonatomic,strong)UIView *starView;
@end

@implementation MyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.fromTop.constant = 0;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.tableView.bounces = NO;
    [self.dataArray addObjectsFromArray:@[@"完成订单",@"我的钱包",@"平台公告",@"设置",@"关于我们"]];
    // Do any additional setup after loading the view.
    
    [[NSNotificationCenter defaultCenter]addObserverForName:kLoginNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
       
        [self loadData];
    }];
    
    [[NSNotificationCenter defaultCenter]addObserverForName:kLogOutNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        
        self.myHeaderView.name.text = @"";
        self.myHeaderView.certificationImage.hidden = YES;
        self.myHeaderView.introduce.text = @"";
        self.myHeaderView.certificationImage.image = nil;
    }];
    
    [self loadData];
}

-(void)loadData
{
    WeakSelf(self)
    [[ConsultantInformation sharedInformation]requestInformation:^(NSError *error) {
        if (error) {
            [MBProgressHUD showError:@"咨询师信息获取失败"];
        }else{
            [Config userDefaultsSetObject:[ConsultantInformation sharedInformation].mobile key:kMobile];
            
            [weakself loadInformation];
        }
    }];
    //获取配置信息
    ConfigApi *api = [ConfigApi new];
    [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        if (kCode(request.responseJSONObject)) {
            [Tool setConsultantTitle:request.responseJSONObject[@"data"][@"counselor_titles"] ];
            [Tool setHospitalTitle:request.responseJSONObject[@"data"][@"hospital_titles"]];
            [Tool setSkilledfieldTitle:request.responseJSONObject[@"data"][@"fields"]];
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        
    }];
}

-(void)loadInformation
{
    ConsultantInformation *information = [ConsultantInformation sharedInformation];
    self.myHeaderView.name.text = information.name;
    self.myHeaderView.certificationImage.hidden = !information.authentication;
    self.myHeaderView.introduce.text = information.consultantTitle;
    [self.myHeaderView.headPortrait sd_setImageWithURL:[NSURL URLWithString:information.avatar] placeholderImage:nil];
    [self starScore:information.evaluate_score];
    [self.myHeaderView.orderFinishedBtn setAttributedTitle:[self data:[NSString stringWithFormat:@"%ld",(long)information.consult_count] describe:@"已咨询" whiteColor:NO] forState:UIControlStateNormal];
    [self.myHeaderView.fansBtn setAttributedTitle:[self data:[NSString stringWithFormat:@"%ld",(long)information.fans_count] describe:@"粉丝" whiteColor:NO] forState:UIControlStateNormal];
}

-(UIView *)addHeaderView
{
    UIView *view = [super addHeaderView];
    [view addSubview:self.myHeaderView];
    [self.headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(view);
    }];
    self.headerViewH.constant = 230;
    return view;
}

-(void)starScore:(float)score
{
    [self.starView removeFromSuperview];
    self.starView = nil;
    
    int count = ceilf(score);
    
    [self.myHeaderView.satisfactionBtn.titleLabel addSubview:self.starView];
    UIImage *star = [UIImage imageNamed:@"StarIcon"];

    for (int i = 0; i < count; i++) {
        UIImageView *imageView = [[UIImageView alloc]init];
        imageView.image = star;
        [self.starView addSubview:imageView];
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.starView);
            make.height.equalTo(@(star.size.height));
            make.width.equalTo(@(star.size.width));
            make.left.equalTo(@(star.size.width * i));
        }];
        
        if (i == count - 1) {
            
            if (count - score != 0) {
                imageView.image = [UIImage imageNamed:@"HalfStar"];
            }
            
            [self.starView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(self.myHeaderView.satisfactionBtn.titleLabel);
                make.width.equalTo(@(count * star.size.width));
                make.height.equalTo(@(19.5));
                make.centerX.equalTo(self.myHeaderView.satisfactionBtn.titleLabel);
            }];
        }
    }
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    [self loadData];

}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellName = @"UITableViewCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellName];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellName];
    }
    
    if (indexPath.row == 0) {
        cell.imageView.image = [UIImage imageNamed:@"SettingOrderIcon"];
    }else if (indexPath.row == 1){
        cell.imageView.image = [UIImage imageNamed:@"SettingWallettIcon"];
    }else if (indexPath.row == 2){
        cell.imageView.image = [UIImage imageNamed:@"SettingAnnouncementIcon"];
    }else if (indexPath.row == 3){
        cell.imageView.image = [UIImage imageNamed:@"SettingSettingIcon"];
    }else if (indexPath.row == 4){
        cell.imageView.image = [UIImage imageNamed:@"SettingAboutIcon"];
    }
    
    cell.textLabel.font = [UIFont systemFontOfSize:15];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.text = self.dataArray[indexPath.row];
    return cell;
}


-(NSAttributedString *)data:(NSString *)data describe:(NSString *)describe whiteColor:(BOOL)whiteColor
{
    /*starView 设置颜色盖不住 text 用透明字解决*/
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:data attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13],NSForegroundColorAttributeName:whiteColor?[UIColor clearColor]:k65ACFE}];
    [str appendAttributedString:[[NSAttributedString alloc] initWithString:@"\n"]];
    [str appendAttributedString:[[NSAttributedString alloc]initWithString:describe attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13],NSForegroundColorAttributeName:k666666}]];
    
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    [style setLineSpacing:8];
    [style setAlignment:NSTextAlignmentCenter];
    [str addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, str.length)];
    return str;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 3) {
        [self.navigationController pushViewController:[[SettingTableViewController alloc]init] animated:YES];
    }else if (indexPath.row == 2){
        [self pushViewController:[[AnnouncementViewController alloc]init] animated:YES];
    }else if (indexPath.row == 1){
        [self pushViewController:[[WalletViewController alloc]init] animated:YES];
    }else if (indexPath.row == 0){
        [self pushViewController:[[CompleteOrderViewController alloc]init] animated:YES];
    }
}

-(MyHeaderView *)myHeaderView
{
    if (!_myHeaderView) {
        _myHeaderView = [MyHeaderView ViewWithXib];
        
        _myHeaderView.headPortrait.image = [UIImage imageNamed:@"My_TheDefaultAvatar"];
        
        [_myHeaderView.orderFinishedBtn setAttributedTitle:[self data:@"--" describe:@"已咨询" whiteColor:NO] forState:UIControlStateNormal];
        [_myHeaderView.fansBtn setAttributedTitle:[self data:@"--" describe:@"粉丝" whiteColor:NO] forState:UIControlStateNormal];
        [_myHeaderView.satisfactionBtn setAttributedTitle:[self data:@"星" describe:@"满意度" whiteColor:YES] forState:UIControlStateNormal];
        
        UILabel *label = [self satisfactionDetails];
        [_myHeaderView.satisfactionBtn.titleLabel addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(_myHeaderView.satisfactionBtn.titleLabel).with.offset(-1);
            make.left.equalTo(_myHeaderView.satisfactionBtn.titleLabel.mas_right).with.offset(2);
            make.height.equalTo(@(14));
        }];
        if (IPHONE5S || IPHONE4S) {
            _myHeaderView.satisfactionBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -35, 0, 0);
        }else{
            _myHeaderView.satisfactionBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
        }
        
        WeakSelf(self)
        _myHeaderView.buttonAction = ^(id obj) {
            MyHeaderViewBtnType type = [obj integerValue];
            
            if (type == OrderFinished_MyHeaderViewBtnType) {
                
            }else if (type == Fans_MyHeaderViewBtnType){
                FansTableViewController *vc = [[FansTableViewController alloc]init];
                [weakself pushViewController:vc animated:YES];
            }else if (type == Satisfaction_MyHeaderViewBtnType){
                EvaluationViewController *vc = [[EvaluationViewController alloc]init];
                [weakself pushViewController:vc animated:YES];
            }else if (type == Editor_MyHeaderViewBtnType){
                EditDataViewController *vc = [[EditDataViewController alloc]init];
                vc.editor = YES;
                [weakself pushViewController:vc animated:YES];
            }
            
        };
    }
    return _myHeaderView;
}

-(UILabel *)satisfactionDetails
{
    UILabel *label = [[UILabel alloc]init];
    label.font = [UIFont systemFontOfSize:_myHeaderView.satisfactionBtn.titleLabel.font.pointSize - 3];
    label.text = @" 查看详情 ";
    label.textColor = [UIColor whiteColor];
    label.backgroundColor = k65ACFE;
    [label roundedCorners_5PX];
    return label;
}

-(UIView *)starView
{
    if (!_starView) {
        _starView = [[UIView alloc]init];
    }
    return _starView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
